package com.atguigu.gmall.cart.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.feign.GmallPmsClient;
import com.atguigu.gmall.cart.mapper.CartMapper;
import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.pms.entity.SkuEntity;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.smartcardio.CardException;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * MQ监听器
 *
 * @author Jia Fa
 * @create 2021-12-20 19:27
 */
@Component
public class CartListener {

    @Autowired
    private GmallPmsClient pmsClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CartMapper cartMapper;

    private static final String KEY_PREFIX = "cart:info:"; // 购物车前缀

    private static final String PRICE_PREFIX = "cart:price:";  // 价格缓存key

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("CART_PRICE_QUEUE"),
            exchange = @Exchange(value = "PMS_ITEM_EXCHANGE", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC),
            key = {"price.update"}
    ))
    // 监听pms商品价格改变信息
    public void syncListener(Long spuId, Channel channel, Message message) throws IOException {
        // 根据spuId  查询旗下所有sku的信息
        ResponseVo<List<SkuEntity>> listResponseVo = this.pmsClient.querySkuBySpuId(spuId);
        List<SkuEntity> skuEntities = listResponseVo.getData();
        if (CollectionUtils.isEmpty(skuEntities)) {
            // 手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        //遍历sku
        skuEntities.forEach(skuEntity -> {
            // 更新实时价格信息  setIfAbsent Redis中存在该商品再进行修改
            this.redisTemplate.opsForValue().setIfPresent(PRICE_PREFIX + skuEntity.getId(), skuEntity.getPrice().toString());
        });
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 监听订单生成删除购物车中选中的记录及删除数据库中相应的购物车记录
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("CART_DELETE_QUEUE"),
            exchange = @Exchange(value = "ORDER_EXCHANGE",ignoreDeclarationExceptions = "true",type = ExchangeTypes.TOPIC),
            key = {"cart.delete"}
    ))
    public void deleteCart(Map<String,Object> map,Channel channel,Message message) throws IOException {
        if (CollectionUtils.isEmpty(map)){
            // 如果map为null 则确认签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }

        // 获取消息的内容
        String userId = map.get("userId").toString();
        String skuIdsJson = map.get("skuIds").toString();
        // 将集合转为string类型 方便Redis使用
        List<String> skuIds = JSON.parseArray(skuIdsJson, String.class);

        // 判断数据是否为空
        if (userId==null || CollectionUtils.isEmpty(skuIds)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }

        // 清空Redis购物车相应数据
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
        hashOps.delete(skuIds.toArray()); // 转为数组清空

        // 删除数据库
        this.cartMapper.delete(new UpdateWrapper<Cart>().eq("user_id", userId).in("sku_id", skuIds));
    }
}
